package com.dly.blog.utile;

import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.dly.blog.content.StringContent;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @Author: DaiLiYu
 * @Date: 2023/7/17 13:55
 */
@Slf4j
public class WebUtils {

    private static final String LOCALHOST_IP1 = "127.0.0.1";

    private static final String LOCALHOST_IP = "0:0:0:0:0:0:0:1";

    public static String getClientIp(HttpServletRequest request) {
        Assert.notNull(request, "HttpServletRequest is null");
        // X-Original-Forwarded-For 主要是为了在K8S环境下获取真实的IP
        String ip = request.getHeader("X-Original-Forwarded-For");
        if(StringUtils.isBlank(ip) || StringContent.UNKNOWN.equalsIgnoreCase(ip)) {
            ip =   getClientIP(request);
        }
        if (StringUtils.isEmpty(ip) || StringContent.UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if(StringUtils.isNotBlank(ip)) {
            ip = ip.split(StringPool.COMMA)[0];
            if (LOCALHOST_IP1.equalsIgnoreCase(ip) || LOCALHOST_IP.equalsIgnoreCase(ip)) {
                //根据网卡取本机配置的IP
                InetAddress iNet = null;
                try {
                    iNet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    log.error("getClientIp error: {}", e.getMessage());
                }
                ip = iNet.getHostAddress();
            }
        }
        return ip;
    }

    public static String getClientIP(HttpServletRequest request, String... otherHeaderNames) {
        String[] headers = new String[]{"X-Forwarded-For", "X-Real-IP", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR"};
        if (ArrayUtil.isNotEmpty(otherHeaderNames)) {
            headers = (String[]) ArrayUtil.addAll(new String[][]{headers, otherHeaderNames});
        }
        return getClientIPByHeader(request, headers);
    }

    public static String getClientIPByHeader(HttpServletRequest request, String... headerNames) {
        String[] var3 = headerNames;
        int var4 = headerNames.length;

        String ip;
        for(int var5 = 0; var5 < var4; ++var5) {
            String header = var3[var5];
            ip = request.getHeader(header);
            if (!NetUtil.isUnknown(ip)) {
                return NetUtil.getMultistageReverseProxyIp(ip);
            }
        }

        ip = request.getRemoteAddr();
        return NetUtil.getMultistageReverseProxyIp(ip);
    }
}
